﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using COMOSOFT.Class;
using DevExpress.XtraReports.UI;
using COMOSOFT.Production.Report;
using DevExpress.LookAndFeel;
using System.IO;

namespace COMOSOFT.ShippingManagement.Forms
{
    public partial class FrmShipMent : Form
    {
        ClassShare cls = new ClassShare("FrmShipMent");
        string strsql = null,strfilename;
        int iSAID,iInvID,iMPO,iDocID,iApprover;
        DataTable dtbContractNo,dtbAllowModify,dtbPinCode,dtbEID;
        bool ballow=true,bAllowModify=true,bAllowSubmit=false;
        List<int> ListDDID = new List<int>();
        USC.UscrptInvoice prtInvoice = null;       

        public FrmShipMent(int _SAID,int _InvID)
        {
            InitializeComponent();
            this.iSAID = _SAID;
            this.iInvID = _InvID;            
        }

        private void AllowSubmit()
        {
            dtbAllowModify=cls.GetData("sp_InvoiceAlowSubmit", new string[] { "@InvID", "@EID" }, new object[] { iInvID, ClassShare.Usid });
            if (dtbAllowModify.Rows.Count > 0)
                bAllowSubmit = true;
            else
                bAllowSubmit = false;
        }

        #region[AllowModify]
        private void AllowModify()
        {
            dtbAllowModify = cls.GetData("sp_InvoiceAllowMoidfy", new string[] {"@InvID","@Creator"}, new object[] {iInvID,ClassShare.Usid});
            if (dtbAllowModify.Rows.Count > 0)
            {
                bAllowModify= true;
                txtcmpincode.Properties.Buttons[1].Enabled = false;
            }
            else
                bAllowModify= false;
        }
        #endregion

        #region[LoadData]
        public void LoadData()
        {
            try
            {
                if (iSAID > 0)
                {
                    shippingAdviseTableAdapter.Fill(dataSet_ShipMent.ShippingAdvise, iSAID);
                    deliveryMasterTableAdapter.Fill(dataSet_ShipMent.DeliveryMaster, iSAID);
                    sp_ShippingChoosePOTableAdapter.Fill(dataSet_ShipMent.sp_ShippingChoosePO, iSAID);
                    xtraTabPage_Invoice.PageVisible = true;
                    if (splitContainerControl_ShippingAdvice.Enabled == false)
                        splitContainerControl_ShippingAdvice.Enabled = true;
                }
                if (iInvID > 0)
                {
                    AllowSubmit();
                    if (bAllowSubmit == true)
                        groupSubmit.Enabled = true;
                    xtraTabPage_Submit.PageVisible = true;
                    sp_InvDetailsTableAdapter.Fill(dataSet_ShipMent.sp_InvDetails, iInvID);
                    dtbContractNo = dataSet_ShipMent.sp_InvDetails;
                    iMPO = Convert.ToInt32(dtbContractNo.Rows[0]["MPOID"]);                   
                    invoiceExtraLibraryTableAdapter.Fill(this.dataSet_ShipMent.InvoiceExtraLibrary);
                    invoiceMasterTableAdapter.Fill(this.dataSet_ShipMent.InvoiceMaster,iInvID);
                    invoiceExtraTableAdapter.Fill(dataSet_ShipMent.InvoiceExtra, iInvID);
                    invDocumentTableAdapter.Fill(dataSet_ShipMent.InvDocument, iInvID);
                    AllowModify();
                    sp_InvoiceCommentListTableAdapter.Fill(dataSet_ShipMent.sp_InvoiceCommentList, iInvID);
                    if (splitContainerControl_Invoice.Enabled == false)
                        splitContainerControl_Invoice.Enabled = true;
                    if (bnt_gotosubmit.Enabled == false)
                        bnt_gotosubmit.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Update Master]
        public void AddNewMaster()
        {
            shippingAdviseBindingSource.AddNew();
            txtETA.EditValue = DateTime.Now;
            txtETD.EditValue = DateTime.Now;            
        }
        public void UpdateData(string com)
        {
            try
            {
                if (com == "Update")
                {
                    shippingAdviseBindingSource.EndEdit();
                    shippingAdviseTableAdapter.Update(dataSet_ShipMent.ShippingAdvise);                    
                    dataSet_ShipMent.ShippingAdvise.AcceptChanges();
                    if (iSAID == -1)
                    {
                        iSAID = Convert.ToInt32(txtSAID.EditValue);
                        foreach(int DID in ClassShare.ListDID)
                        {
                            strsql = "update DeliveryMaster set SAID=@SAID where DID=@DID";
                            cls.UpdateDataTypeText(strsql, new string[] {"@SAID","@DID"}, new object[] {iSAID,DID});
                        }                       
                    }    
                }
                else
                {
                    if (MessageBox.Show("Are you sure delete item?", "Deletion..", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        dataSet_ShipMent.ShippingAdvise.Rows[0].Delete();
                        shippingAdviseTableAdapter.Update(dataSet_ShipMent.ShippingAdvise);
                        dataSet_ShipMent.ShippingAdvise.AcceptChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Update Container]
        private void gridView_Container_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                deliveryMasterBindingSource.EndEdit();
                deliveryMasterTableAdapter.Update(dataSet_ShipMent.DeliveryMaster);
                dataSet_ShipMent.DeliveryMaster.AcceptChanges();
                deliveryMasterTableAdapter.Fill(dataSet_ShipMent.DeliveryMaster, iSAID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void bnt_gotosubmit_Click(object sender, EventArgs e)
        {
            try
            {
                xtraTabControl_Shipping.SelectedTabPageIndex = 2;
                xtraTabPage_Submit.PageVisible = true;
                if (prtInvoice != null && !prtInvoice.IsDisposed)
                {
                    prtInvoice.LoadData();
                }
                else
                {
                    prtInvoice = new USC.UscrptInvoice(iInvID, txtType.EditValue.ToString());
                    splitContainerControl_Submit.Panel1.Controls.Add(prtInvoice);
                    prtInvoice.Dock = DockStyle.Fill;
                    prtInvoice.LoadData();
                    prtInvoice.Show();                 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void FrmShipMent_Load(object sender, EventArgs e)
        {            
            this.employeeTableAdapter.Fill(this.dataSet_ShipMent.Employee);
            this.costingExtraLibraryTableAdapter.Fill(this.dataSet_ShipMent.CostingExtraLibrary);
        }

        #region[UpdateInvoice]
        public void AddnewInvoice()
        {
            invoiceMasterBindingSource.AddNew();
            txtInvSA.EditValue = iSAID;
            txtPIDate.EditValue = DateTime.Now;
            txtLCDate.EditValue = DateTime.Now;
            txtInvDate.EditValue = DateTime.Now;
            txtType.SelectedIndex = 0;
            txtShippingTerm.SelectedIndex = 0;
            txtCreator.EditValue = Convert.ToInt64(ClassShare.Usid);
        }
        public void UpdateInvoice(string com)
        {
            try
            {
                if (bAllowModify == true)
                {
                    if (com == "Update")
                    {
                        invoiceMasterBindingSource.EndEdit();
                        invoiceMasterTableAdapter.Update(dataSet_ShipMent.InvoiceMaster);
                        dataSet_ShipMent.InvoiceMaster.AcceptChanges();
                        if (splitContainerControl_Invoice.Enabled == false)
                            splitContainerControl_Invoice.Enabled = true;
                        if (bnt_gotosubmit.Enabled == false)
                            bnt_gotosubmit.Enabled = true;
                        if (iInvID == -1)
                        {
                            iInvID = Convert.ToInt32(txtInvID.EditValue);
                            foreach (int DDID in ListDDID)
                            {
                                strsql = "update DeliveryDetail set InvID=@InvID where DDID=@DDID";
                                cls.UpdateDataTypeText(strsql, new string[] { "@InvID", "@DDID" }, new object[] { iInvID, DDID });
                            }
                        }
                        sp_InvDetailsTableAdapter.Fill(dataSet_ShipMent.sp_InvDetails, iInvID);
                    }
                    else
                    {
                        if (MessageBox.Show("Are you sure delete item?", "Deletion..", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            dataSet_ShipMent.InvoiceMaster.Rows[0].Delete();
                            invoiceMasterTableAdapter.Update(dataSet_ShipMent.InvoiceMaster);
                            dataSet_ShipMent.InvoiceMaster.AcceptChanges();
                            iInvID = -1;
                        }
                    }
                    invoiceMasterTableAdapter.Fill(dataSet_ShipMent.InvoiceMaster, iInvID);
                }
                else
                {
                    MessageBox.Show("Invoice is locked not modify!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void RefreshInvoice()
        {
            try
            {
                invoiceExtraLibraryTableAdapter.Fill(this.dataSet_ShipMent.InvoiceExtraLibrary);
                invoiceMasterTableAdapter.Fill(this.dataSet_ShipMent.InvoiceMaster, iInvID);
                invoiceExtraTableAdapter.Fill(dataSet_ShipMent.InvoiceExtra, iInvID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region[Select PO Create Invoice]
        private void createToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                GridView view = gridView_SelectPO as GridView;
                ListDDID.Clear();
                int[] arPO = view.GetSelectedRows();
                foreach (int index in arPO)
                {
                    if ((Convert.IsDBNull(view.GetDataRow(index)["InvID"]) ? "" : view.GetDataRow(index)["InvID"].ToString()) != "")
                    {
                        ballow = false;
                        break;
                    }
                    ListDDID.Add(Convert.ToInt32(view.GetDataRow(index)["DDID"]));
                    iMPO = Convert.ToInt32(view.GetDataRow(index)["MPOID"]);
                }
                if (ballow == true)
                {
                    xtraTabControl_Shipping.SelectedTabPageIndex = 1;
                    xtraTabPage_Invoice.PageVisible = true;
                    AddnewInvoice();
                }
                else
                {
                    MessageBox.Show("PO have exists invoice. Please check again!");
                }
                ballow = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void xtraTabControl_Shipping_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            ClassShare.iTabShippingIndex = xtraTabControl_Shipping.SelectedTabPageIndex;
        }


        private void txtType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtType.SelectedIndex == 0)
                {
                    panel_LC.Visible = true;
                    panelTTDP.Visible = false;
                }
                else
                {
                    panel_LC.Visible = false;
                    panelTTDP.Visible = true;

                    strsql = "select ContSalePO,IssuaDate " +
                               " from MasterPO " +
                               " where MPOID= @MPOID ";
                    dtbContractNo = cls.GetDataSql(strsql, new string[] { "@MPOID" }, new object[] { iMPO });
                    txtContractNo.EditValue = dtbContractNo.Rows[0]["ContSalePO"];
                    txtContractDate.EditValue = Convert.ToDateTime(dtbContractNo.Rows[0]["IssuaDate"]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtContractNo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                txtContractDate.EditValue = Convert.ToDateTime(view.GetFocusedDataRow()["IssuaDate"]);
            }
            catch
            {
            }
        }

        #region[UpdateExtraPrice]
        private void gridView_Expense_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            gridView_Expense.SetFocusedRowCellValue("InvID", iInvID);
        }

        private void gridView_Expense_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                if (bAllowModify == true)
                {
                    invoiceExtraBindingSource.EndEdit();
                    invoiceExtraTableAdapter.Update(dataSet_ShipMent.InvoiceExtra);
                    dataSet_ShipMent.InvoiceExtra.AcceptChanges();
                    invoiceExtraTableAdapter.Fill(dataSet_ShipMent.InvoiceExtra, iInvID);
                }
                else
                {
                    MessageBox.Show("Invoice is locked not modify!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }     
        #endregion

        #region[AttachFile]

        private void repositoryAction_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (bAllowModify == true)
                {
                    if (e.Button.Tag.ToString() == "Add")
                    {
                        OpenFileDialog file = new OpenFileDialog();
                        file.Multiselect = true;
                        if (file.ShowDialog() == DialogResult.OK)
                        {
                            for (int i = 0; i < file.FileNames.Length; i++)
                            {
                                string name = Path.GetFileName(file.FileNames[i]);
                                strsql = "insert into InvDocument (InvID,DocType,DocName,DateUpdate,Creator) " +
                                        " values (@InvID,@DocType,@DocName,@DateUpdate,@Creator)";
                                cls.UpdateDataTypeText(strsql, new string[] { "@InvID", "@DocType", "@DocName", "@DateUpdate", "@Creator" },
                                                               new object[] { iInvID, "Document", name, DateTime.Now, ClassShare.Usid });
                                cls.UploadFile(file.FileNames[i], ClassShare.ftpJobAssign);
                            }
                        }
                    }
                    else
                    {

                        iDocID = Convert.ToInt32(gridView_AttachFile.GetFocusedDataRow()["DOCID"]);
                        strsql = "delete from InvDocument where DOCID=@DOCID";
                        cls.UpdateDataTypeText(strsql, new string[] { "@DOCID" }, new object[] { iDocID });
                    }
                    invDocumentTableAdapter.Fill(dataSet_ShipMent.InvDocument, iInvID);
                }
                else
                {
                    MessageBox.Show("Invoice is locked not modify!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        

        private void repositoryname_Click(object sender, EventArgs e)
        {
            try
            {
                strfilename = gridView_AttachFile.GetFocusedDataRow()["DocName"].ToString();
                if (!File.Exists(ClassShare.lcJobAsign + strfilename))
                    cls.Dowload(ClassShare.ftpJobAssign, ClassShare.lcJobAsign, strfilename);
                System.Diagnostics.Process.Start(ClassShare.lcJobAsign + strfilename);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void bnt_UpdateINV_Click(object sender, EventArgs e)
        {
            xtraTabControl_Shipping.SelectedTabPageIndex = 1;
        }

        #region[Submit]
        private void txtcmpincode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                strsql = "select PinCode from Employee where EID=@EID and PinCode=@PinCode";
                dtbPinCode = cls.GetDataSql(strsql, new string[] { "@EID", "@PinCode" }, new object[] { ClassShare.Usid, txtcmpincode.Text });
                if (dtbPinCode.Rows.Count > 0)
                {
                    if (e.Button.Tag.ToString() == "Submit")
                    {         
                   
                            strsql = "select Leader,LD.FullName as Name from Employee left join (select EID, FullName from Employee) as LD on Employee.Leader=LD.EID where Employee.EID=@EID";
                            dtbEID = cls.GetDataSql(strsql, new string[] { "@EID" }, new object[] { ClassShare.Usid });
                            iApprover = Convert.ToInt32(dtbEID.Rows[0]["Leader"]);
                            cls.UpdateData("sp_InvoiceSubmitUpdate", new string[] { "@InvID", "@Submiter", "@Approver", "@SubmitDate", "@Status" },
                                                                     new object[] { iInvID, ClassShare.Usid, iApprover, DateTime.Now, "Submited" });
                            if (ClassShare.Usid == 22)
                            {
                                strsql = "update InvoiceMaster set [Status]=@Status,WaitingFor=@WaitingFor,[Signature]=@Signature where InvID=@InvID";
                                cls.UpdateDataTypeText(strsql, new string[] { "@InvID", "@Status", "@WaitingFor", "@Signature" }, new object[] { iInvID, "Close", "Finished",ClassShare.Usname.ToString() });
                            }
                            else
                            {
                                strsql = "update InvoiceMaster set [Status]=@Status,WaitingFor=@WaitingFor where InvID=@InvID";
                                cls.UpdateDataTypeText(strsql, new string[] { "@InvID", "@Status", "@WaitingFor" }, new object[] { iInvID, "On going", dtbEID.Rows[0]["Name"].ToString() });
                            }
                            MessageBox.Show("Submit successfully!");                                            
                    }
                    else
                    {
                        strsql="select FullName "+
                               " from InvoiceSubmit left join Employee on InvoiceSubmit.Submiter=Employee.EID "+
                               " where InvID=@InvID and Approver=@EID ";
                        dtbEID=cls.GetDataSql(strsql, new string[] { "@InvID", "@EID" }, new object[] { iInvID, ClassShare.Usid });

                        cls.UpdateData("sp_InvoiceReject", new string[] { "@InvID", "@EID", "@Status", "@WaitingFor" }, new object[] { iInvID, ClassShare.Usid, "Reject", dtbEID.Rows[0]["FullName"].ToString() });
                        MessageBox.Show("Reject successfully!");                        
                    }
                    if (txtcmcomment.EditValue.ToString() != "")
                    {
                        strsql = "insert into InvoiceFollowUp (InvID,[Action],ActionDate,Handler) " +
                                 " values (@InvId,@Action,@ActionDate,@Handler)";
                        cls.UpdateDataTypeText(strsql, new string[] { "@InvId", "@Action", "@ActionDate", "@Handler" }, new object[] { iInvID, txtcmcomment.EditValue.ToString(),DateTime.Now,ClassShare.Usid });
                    }
                    txtcmcomment.Text = "";
                    txtcmpincode.Text = "";
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Pincode incorrect! Please try again!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion
    }   
}
